/**
 * import 导入静态文件
 * @return {[type]} 
 */
var STATIC_VERSION = STATIC_VERSION || '20120305';
var JS_PATH = JS_PATH || './static/js';
var COOKIE_DOMAIN = COOKIE_DOMAIN || '.xinranzixun.com';

//首页优化201212：从indexJson.js中拷贝变量
var ytJson =[
	{"key":"9","text":"不限"},
	{"key":"1","text":"经营周转"},
	{"key":"2","text":"个人消费"},
	{"key":"3","text":"贷款买车"},
	{"key":"4","text":"按揭买房"}
];
var zysfJson={"1":"民营企业主","2":"个体工商户","3":"在职员工"}

function include(filePath){
	var self = arguments.callee,
		conf = self._config,
		cache = self._cache = self._cache || {},
		url = self.toUrl(filePath);
	var globalEval = function( data, hint) {
		if ( data && /\S/.test( data ) ) {
			data = '"nope";\r\n' + data + "\r\n////@ sourceURL=" + hint;
			// We use execScript on Internet Explorer
			// We use an anonymous function so that context is window
			// rather than jQuery in Firefox
			( window.execScript || function( data ) {
				window[ "eval" ].call( window, data );
				// var scr = $('<script type="text/javascript"></script>');
				// scr[0].appendChild(document.createTextNode(data));
				// scr.appendTo($('head'));
			} )( data );
		}
	};
	//已加载
	if (cache[url]) { return false};
	cache[url] = true;
	$.ajax(url,{
		async:false,
		converters:{'text script':function(text){return text;}},
		success:function(text){
			globalEval(text, url);
		}
	});
}

//初始化数据
include._config = {
	baseUrl:''
};
include._cache = {};

/**
 * 将模块名称转成url格式.
 */
include.toUrl = function (mod){
	return include._config.baseUrl + mod.replace(/\.js$/i,'') + '.js' + '?v=' + STATIC_VERSION;
};

/**
 * 添加配置文件
 * @param  {[type]} conf [description]
 * @return {[type]}
 */
include.config = function(conf){
	for(var p in conf){
		if ( conf.hasOwnProperty(p)) {
			include._config[p] = conf[p];
		};
	}
};
/**
 * 标识已经加载的文件
 * 注意: 部署程序在合并文件时,需要在文件结尾添加 include.markLoaded(filePathByBaseUrl); 以防止页面重复加载
 * @param  {[type]} filePath [description]
 * @return {[type]}
 */
include.markLoaded = function(filePath){
	include._cache[include.toUrl(filePath)] = true;
}


/**
 * 定义基础路径
 */
include.config({
	baseUrl: JS_PATH + '/'
});

/**
 * 1. 引入google统计
 */
include("mod/cookie")
//include("google");
include("mod/poplayer");
include("mod/validator");
/*
*引用常用模块
*/
include('mod/simple_autocomplete');
include('mod/simple_dropdown');
//提示框
include("mod/tooltip")
//自定义接口:loan_limit
$.autocompleteUiApi.loan_limit = function(target,val,fn){
    //默认值
    if(!target.data('defaultlist'))
        target.data('defaultlist',$('[role=autocomplete-list]',$(target.data('target'))).html());

    if(/[0-9.]+$/.test(val)){

      if(val<1000 && val > 0){

        var ret = [],
            mval = parseInt(val*10),
            rval = parseInt(val*100);

        ret.push({val:val,txt:val+" 万元",checked:true});

        mval<1000 && ret.push({val:mval,txt:mval+" 万元"});
        rval<1000 && ret.push({val:rval,txt:rval+" 万元"});

        fn(ret);
        $('#bx_sb_loan_wrap div.sb_tip_text').css('color','#fff')

      }else{
          $.autocompleteUiApi.clearAutoCompleteList();
          val.length > 4 && target.val(val.substr(0,4));
          if(val.length>=4){
            $('#bx_sb_loan_wrap div.sb_tip_text').css('color','#ffdd00')
          }
      }

    }else{
      $.autocompleteUiApi.clearAutoCompleteList();

      if(val===''){
          fn(target.data('defaultlist'))
      }else{
        //target.val('')
      }
    }
}

//email，自动提醒api
$.autocompleteUiApi.email = function(target,val,fn){
	if(val==='')
		return;
	
	val = val.replace(/@.*/,'');

	var ret = [],
		email = ['qq.com','126.com','163.com','yahoo.com.cn','gmail.com'];
	for(var i=0;i<email.length;i++){
		ret.push({val:val+'@'+email[i],txt:val+'@'+email[i]});
	}

	fn(ret);
}


$(function(){
$('ul[role=menu]').on('click','li a',function(e){
      e.preventDefault();
      
      $this = $(this),
      val  = $this.data('val'),
      $parent = $this.parent().parent().parent();

      if(val && val>0){
        $parent.find('input[data-autocpt=autocomplete]').val(val);
      }else if(val == 0){
        $parent.find('input[data-autocpt=autocomplete]').focus();
      }
});

$('input[data-autocpt=autocomplete]').focus(function(){ 
  $(this).parent().find('span.sb_inp_suffix').css('color','#d3d3d3')
}).blur(function(){
  $(this).parent().find('span.sb_inp_suffix').css('color','#333')
}).click(function(){
  if($(this).val() === ''){
    $(this).keyup();
  }
})
});

//异步探针模块
include('mod/sync_fork');
//
include('mod/poplayer_fork');

window.R = window.R || {};
/**
 * 获取URL中的参数
 * @param param 参数名
 * @return 若传入参数名,则返回对应值;否则返回全部URL参数的json
 */
R.urlParam = function(param){
  var params = {};
  window.location.href.replace(/(?:\?|&)([^=]*)=([^&]*)/, function($0, key, value){
    params[key] = value;
  });
  return param ? params[param] : params;
};

function escapeReg(source) {
	    return String(source)
		        .replace(new RegExp("([.*+?^=!:\x24{}()|[\\]\/\\\\])", "g"), '\\\x241');
};
R.getQueryFromString = function(key,str){
	if(!str||!key)
		return ;
	
	var reg = new RegExp(
            "(^|&|\\?|#)" 
            + escapeReg(key) 
            + "=([^&#]*)(&|\x24|#)", 
            "");
    var match = str.match(reg);
    if (match) {
        return match[2];
    }
}
/**
 * 设置cookie,
 * @param options 
 *  options.expires: 过期时间(天), 默认365天
 */
R.setCookie = function(key, value, options){
  $.cookie(key, value, $.extend(options||{},{
    expires:365, //默认一年
    path:'/',
    domain:COOKIE_DOMAIN
  }));
};
/**
 * 将城市信息写入cookie
 * @param city cityDomain, 形如beijing的城市拼音
 */
R.setCity = function(city){
  R.setCookie('cityDomain', city);
  $.cookie('has_chose_city', 1, {expires:0, path:'/', domain:COOKIE_DOMAIN});
};
/**
 * 将城市信息写入cookie,用于异地申请判断
 * @param city cityDomain, 形如beijing的城市拼音
 */
R.setMyCity = function(city){
  $.cookie('my_city', city, {expires:0, path:'/', domain:COOKIE_DOMAIN});
};
/**
 * 异步加载script, 主要用于第三方非依赖资源加载.
 * @param  {[type]} src [description]
 * @return {[type]}     [description]
 */
R.asyncLoadScript = function(src){
  var tag = document.createElement('script'); 
  tag.type = 'text/javascript'; 
  tag.async = true;
  tag.defer = 'defer';
  tag.src = src;
  var s = document.getElementsByTagName('script')[0]; 
  s.parentNode.insertBefore(tag, s);
};

$(function(){
  window.PAGE_READY_TIME = new Date().getTime();
  //鼠标hover的样式
  $('[hover-class]').live('mouseenter', function(){
    $(this).addClass($(this).attr('hover-class'));
  }).live('mouseleave', function(){
    $(this).removeClass($(this).attr('hover-class'));
  });

  //点击样式,比如三态按钮
  $('[click-class]').live('mousedown', function(){
    $(this).addClass($(this).attr('click-class'));
  }).live('mouseup', function(){
    $(this).removeClass($(this).attr('click-class'));
  }).live('mouseleave', function(){
    $(this).removeClass($(this).attr('click-class'));
  });

  //初始化 click-url
  $('[click-url]').live('click', function(e){
	var target = e.target;
    var url = $(this).attr('click-url');
    if($(this).is('a') || $(target).is('a')){
      $(this).attr('href', url);
    } else {
    //创建临时a标签
    var referUrl = document.createElement('a');
        referUrl.cssText = "visibility:hidden;position:absolute";
        referUrl.href = url;  
        referUrl.target = "_target";  
        document.body.appendChild(referUrl);  
        referUrl.click();
    }
  }).css('cursor','pointer');

  //初始化header中的城市点击
  R.initCityList();
  //初始layer点击
  $(document).click(hideLayers);
});
R.initCityList = function(){
  /*
  $('#city-list').click(function(evt){
	evt.stopPropagation();
    $('#cities').toggle();
  });
  $('#cities').click(function(evt){
    evt.stopPropagation();
  });
*/
};
/////页面加载时间统计
function loadLogImg(src){
	var img = new Image(),
		now = new Date().getTime();
	
	window['fix_img_'+now] = img;

	img.onload = function(){
		try{
			delete window['fix_img'+now];
			img = null;
		}catch(e){
			window['fix_img'+now] = null;
			img = null;
		}
	}
	img.src = src;
}

$(window).on('load',function(){
	try{
	var now =  new Date().getTime(),
		pageReadyTimes = typeof PAGE_READY_TIME !='undefined'?PAGE_READY_TIME - PAGE_START_TIME:now - PAGE_START_TIME,
		pageLoadedTime = now - PAGE_START_TIME;
	
	loadLogImg('http://g.rong360.com/t.gif?ca='+PAGE_CA+'&tpl='+PAGE_TPL+'&plt='+pageLoadedTime+'&prt='+pageReadyTimes+'&r='+now+'&'+PAGE_USER_FROM+'&city='+PAGE_USER_CITY);
	
	}catch(e){};
});

///////////////////
// 遗留的全局工具方法
///////////////////

/**
 * Set the shortcut of getElementById;
 * @param id: The dom's id.
 */
var g = function(id){
  return typeof id == 'string' ? document.getElementById(id) : id;
};

/**
 * 添加事件响应
 * @param  {[type]} dom       [description]
 * @param  {[type]} eventName [description]
 * @param  {[type]} handler   [description]
 * @return {[type]}
 */
var on = function(dom, eventName, handler){
  if(dom.addEventListener){
    dom.addEventListener(eventName, handler, false);
  } else {
    dom.attachEvent('on' + eventName, handler);
  }
}

/**
 * Toggle the pop div when mouseover and hide when mouseout.
 * @param event: 
 * @param txt: The text shown in the pop div.
 * @param flag: Control the div's stat, shown if flag equals true. 
 */
function overDescription(event, txt, flag) {
  event = event? event: window.event
  var hint = g('hint_over');
  var d = document;
  var scrollTop = window.pageYOffset || d.documentElement.scrollTop || d.body.scrollTop;
  if (flag) {
    hint.innerHTML = txt;
    clientX = event.x ? event.x : event.pageX;
    clientY = event.y ? event.y : event.pageY;
    hint.style.left = clientX + 5 + 'px';
    hint.style.top = (clientY+scrollTop) + 5 + 'px';
    hint.style.display = 'block';
  }else {
    hint.style.display = 'none';
  }
}

/**
 * Graph the rate number to star. Applied evaluated_star div.
 */
function setRateToStar() {
  var value = parseInt(g('evaluated_star').innerHTML);
  var fullStarImg = imgPath + 'star-full.png';
  var semiStarImg = imgPath + 'star-semi.png';
  var emptyStarImg = imgPath + 'star-empty.png';
  var unit = 20;
  var starFullNum = parseInt(value / unit);
  var html = [];
  var t = starFullNum;
  for (var i = 0; i < starFullNum; i ++) {
    html.push('<img src=' + fullStarImg  + ' class="pngfix">');
  }
  if (value % unit > 2) {
    html.push('<img src=' + semiStarImg  + ' class="pngfix">');
    t ++;
  }
  for (var i = 0 ; i < 5 - t; i ++){
    html.push('<img src=' + emptyStarImg +  ' class="pngfix">');
  }

  g('evaluated_star').innerHTML = html.join('');
}

/**
 * Hide all layers in an element.
 * @param el: The specified element.
 */ 
function hideLayers() {
  $('[panes="layer"]').hide();
}


/*获取urlquerys*/
R.getQuerys = function(url){
        if(!url)
            return null;

        var reg = /([^&\\?#]+)=([^&#]*)/g,
            match = url.match(reg),
            ret ={};

        if(match){
            var i=0,l = match.length,item;
            for(;i<l;i+=1){
                item = match[i].split('=');
                if(item.length>1){
                    try{
                       ret[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
                    }catch(e){
                        ret[encodeURI(item[0])] = encodeURI(item[1]);
                    }
                }   
            };  
        }   
        return ret;
    }
